package com.glwan.fixedassetapp.ui.home.Activity;

import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.glwan.fixedassetapp.Adapter.ListableAdapter;
import com.glwan.fixedassetapp.R;
import com.glwan.fixedassetapp.common.ApiConstant;
import com.glwan.fixedassetapp.components.SelectView;
import com.glwan.fixedassetapp.handler.ReaderResponseInterfaces;
import com.glwan.fixedassetapp.helper.KeyCodeReceiver;
import com.glwan.fixedassetapp.helper.RFIDDeviceInterface;
import com.glwan.fixedassetapp.model.ApiResponse;
import com.glwan.fixedassetapp.model.AssetOld;
import com.glwan.fixedassetapp.model.RFIDTagData;
import com.glwan.fixedassetapp.utils.CommonUtil;
import com.glwan.fixedassetapp.utils.GsonUtil;
import com.glwan.fixedassetapp.utils.MMKVKeys;
import com.glwan.fixedassetapp.utils.MMKVSingleton;
import com.glwan.fixedassetapp.utils.OkHttpUtil;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class InventoryTaskActivity extends AppCompatActivity implements ReaderResponseInterfaces.ResponseStatusHandler, ReaderResponseInterfaces.ResponseTagHandler, ReaderResponseInterfaces.ResponseKeyEventHandler {

    private List<Map<String, Object>> parentList = new ArrayList<>();

    private Map<String, Integer> groupTextViewMap = new HashMap<>();

    private ListView listView;

    private ListableAdapter listableAdapter;
    List<String> spinnerValueList = new ArrayList<>();
    List<AssetOld> addressList = new ArrayList<>();
    private SelectView selectView;
    RFIDDeviceInterface rfidDeviceInterface;
    KeyCodeReceiver keyCodeReceiver;
    List<String> scannedList = new ArrayList<>();

    private Activity getActivity() {
        return this;
    }

    //列表
    Callback addressListCallback = new Callback() {
        @Override
        public void onFailure(@NonNull Call call, @NonNull IOException e) {
            CommonUtil.toastShow(getActivity(), e.getMessage(), CommonUtil.ERROR, true);
            //关闭加载框
            CommonUtil.cancelProgressDialog(getActivity());
        }

        @Override
        public void onResponse(@NonNull Call call, Response response) throws IOException {

            ApiResponse<List<AssetOld>> responseData = GsonUtil.fromJson(response, new TypeToken<ApiResponse<List<AssetOld>>>() {
            }.getType());


            if (responseData != null && responseData.isSuccess()) {
                spinnerValueList.clear();
                addressList = responseData.getData();
                for (AssetOld asset : addressList) {
                    spinnerValueList.add(asset.getPlaceOfPreservation());
                }
                runOnUiThread(() -> selectView.setSelectedItem(0));
            } else {
                String msg;
                if (responseData == null || responseData.getMsg() == null) {
                    msg = "请求失败";
                } else {
                    msg = responseData.getMsg();
                }
                CommonUtil.toastShow(getActivity(), msg, CommonUtil.ERROR, true);
            }
            CommonUtil.cancelProgressDialog(getActivity());
        }
    };
    List<String> reportList = new ArrayList<>();
    Callback reportCallback = new Callback() {
        @Override
        public void onFailure(@NonNull Call call, @NonNull IOException e) {
            CommonUtil.toastShow(getActivity(), e.getMessage(), CommonUtil.ERROR, true);
            //关闭加载框
            CommonUtil.cancelProgressDialog(getActivity());
        }

        @Override
        public void onResponse(@NonNull Call call, Response response) throws IOException {

            ApiResponse<List<Map<String, Object>>> responseData = GsonUtil.fromJson(response, new TypeToken<ApiResponse<List<Map<String, Object>>>>() {
            }.getType());


            if (responseData != null && responseData.isSuccess()) {
                parentList.addAll(responseData.getData());
                runOnUiThread(() -> {
                    listableAdapter.notifyDataSetChanged();
                });
            } else {
                String msg;
                if (responseData == null || responseData.getMsg() == null) {
                    msg = "请求失败";
                } else {
                    msg = responseData.getMsg();
                }
                CommonUtil.toastShow(getActivity(), msg, CommonUtil.ERROR, true);
            }
            CommonUtil.cancelProgressDialog(getActivity());
        }
    };
    private Button btScanning;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_home_inventory_task);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        setTitle(getString(R.string.inventoryTask));
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        selectView = findViewById(R.id.selectView);
        selectView.setAdapter(new ArrayAdapter<>(getActivity(), R.layout.support_simple_spinner_dropdown_item, spinnerValueList));
        btScanning = findViewById(R.id.btScanning);

        rfidDeviceInterface = RFIDDeviceInterface.getInstance(Build.BRAND, this);
        if (rfidDeviceInterface != null && !rfidDeviceInterface.isConnected()) {
            connectReader();
        }

        btScanning.setOnClickListener(view -> {
            inventory();
//            String s = "{\n" +
//                    "  \"success\": true,\n" +
//                    "  \"data\": [\n" +
//                    "    {\n" +
//                    "      \"fdSerialnumber\": \"130000000161\",\n" +
//                    "        \"fdName\": \"华为平板\",\n" +
//                    "      \"fdStatus\": \"4\"\n" +
//                    "    }\n" +
//                    "  ],\n" +
//                    "  \"msg\": \"资产盘点完成\",\n" +
//                    "  \"code\": null\n" +
//                    "}";
//            ApiResponse<List<Map<String, Object>>> responseData = GsonUtil.fromJson(s, new TypeToken<ApiResponse<List<Map<String, Object>>>>() {
//            }.getType());
//            if (responseData != null && responseData.isSuccess()) {
//                parentList.addAll(responseData.getData());
//            }
//            listableAdapter.notifyDataSetChanged();
        });

        initData();
    }

    //返回主界面
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

    private void initData() {
        groupTextViewMap.put("sortNo", R.id.sortNo);
        groupTextViewMap.put("fdName", R.id.fdYzCardName);
        groupTextViewMap.put("fdSerialnumber", R.id.fdId);
        groupTextViewMap.put("fdStatus", R.id.status);
        listView = findViewById(R.id.inventoryTaskList);
        listableAdapter = new ListableAdapter(getActivity(), parentList, groupTextViewMap, R.layout.offline_inventory_item);
        listView.setAdapter(listableAdapter);
        getAddressList();
    }

    private void connectReader() {
        Handler handler = new Handler();
        handler.postDelayed(() -> {
            if (rfidDeviceInterface != null) {
                rfidDeviceInterface.connect();
            } else {
                CommonUtil.toastShow(getActivity(), "当前设备不支持RFID", CommonUtil.ERROR, true);
            }
        }, 0);
    }

    /**
     * 获取数据
     */
    private void getAddressList() {
        //打开加载框
        CommonUtil.openProgressDialog(getActivity(), getString(R.string.loading));
        //获取服务地址和session
        String session = MMKVSingleton.getString(MMKVKeys.KEY_SESSION, "");
        String address = MMKVSingleton.getString(MMKVKeys.KEY_DOMAIN, "");
        String GET_TASK_LIST_URL = address + ApiConstant.GET_ADDRESS_LIST;
        Map<String, Object> headerMap = new HashMap<>();
        headerMap.put("Cookie", "SESSION=" + session);
        //获取列表
        OkHttpUtil.postNew(GET_TASK_LIST_URL, "text/plain", headerMap, null, addressListCallback);
    }

    @Override
    protected void onResume() {
        super.onResume();
        keyCodeReceiver = KeyCodeReceiver.getInstance(this);
        keyCodeReceiver.registerKeyCodeReceiver();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (rfidDeviceInterface != null)
            rfidDeviceInterface.stopInventory();
        if (keyCodeReceiver != null)
            keyCodeReceiver.unregisterReceiver();
        btScanning.setText(getString(R.string.startScanning));
    }

    /**
     * 扳机按键返回处理事件
     */
    @Override
    public void handleResponse() {
        inventory();
    }

    private void inventory() {
        if (getString(R.string.startScanning).equals(btScanning.getText().toString())) {
            btScanning.setText(getString(R.string.stopScanning));
            rfidDeviceInterface.changeInventoryMode(0, null);
            rfidDeviceInterface.startInventory();
        } else {
            btScanning.setText(getString(R.string.startScanning));
            rfidDeviceInterface.stopInventory();

            reportScannedList();
        }
    }

    private void reportScannedList() {
        reportList.addAll(scannedList);
        scannedList.clear();
        reportScannedData();
    }

    @Override
    public void handleStatusResponse(boolean open) {
        if (open) {
            rfidDeviceInterface.changeInventoryMode(0, null);
        } else {
            reportScannedList();
        }
    }

    @Override
    public void handleResponse(RFIDTagData data) {
        String epc = data.getEpc();
        if (epc == null || epc.length() > 15 || epc.length() < 10 || scannedList.contains(epc)) {
            return;
        }
        scannedList.add(epc);
        if (scannedList.size() > 50) {
            reportScannedList();
        }
    }

    private String getSelectedType() {
        String selectedItem = selectView.getSelectTextValue();
        for (AssetOld asset : addressList) {
            if (TextUtils.equals(selectedItem, asset.getPlaceOfPreservation())) {
                return asset.getId();
            }
        }
        return "";
    }

    /**
     * 获取数据
     */
    private void reportScannedData() {
        //打开加载框
        CommonUtil.openProgressDialog(getActivity(), getString(R.string.loading));
        //获取服务地址和session
        String session = MMKVSingleton.getString(MMKVKeys.KEY_SESSION, "");
        String address = MMKVSingleton.getString(MMKVKeys.KEY_DOMAIN, "");
        String GET_TASK_LIST_URL = address + ApiConstant.UPLOAD_RFID_LIST;
        Map<String, Object> headerMap = new HashMap<>();
        headerMap.put("Cookie", "SESSION=" + session);
        JsonObject jsonObject = new JsonObject();
        JsonArray jsonArray = new JsonArray();
        reportList.forEach(jsonArray::add);
        jsonObject.add("data", jsonArray);
        jsonObject.addProperty("loginName", MMKVSingleton.getString(MMKVKeys.KEY_USERNAME, ""));
        jsonObject.addProperty("addressId", getSelectedType());
        //获取列表
        OkHttpUtil.postNew(GET_TASK_LIST_URL, "application/json", headerMap, jsonObject, reportCallback);
    }
}

